package com.jdd.modules.area.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jdd.common.api.vo.Result;
import com.jdd.common.aspect.annotation.AutoLog;
import com.jdd.common.exception.JddException;
import com.jdd.common.system.query.QueryGenerator;
import com.jdd.common.system.vo.LoginUser;
import com.jdd.common.util.*;
import com.jdd.modules.area.entity.ChargeRules;
import com.jdd.modules.area.entity.ChargeRulesModule;
import com.jdd.modules.area.service.IChargeRulesModuleService;
import com.jdd.modules.area.service.IChargeRulesService;
import com.jdd.modules.sdkidentifyresultpushlog.service.ChargeFeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Description: 停车场计费规则表
 * @Author: jdd
 * @Date: 2021-07-13
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "停车场计费规则表")
@RestController
@RequestMapping("/parking/chargeRules")
public class ChargeRulesController {
    @Resource
    private IChargeRulesService chargeRulesService;
    @Resource
    private IChargeRulesModuleService chargeRulesModuleService;
    @Resource
    private ChargeFeeService chargeFeeService;
    @Resource
    private ChargeFeeUtils chargeFeeUtils;
    @Resource
    private RestTemplate restTemplate;
    /**
     * 分页列表查询
     *
     * @param chargeRules
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "停车场计费规则表-分页列表查询")
    @ApiOperation(value = "停车场计费规则表-分页列表查询", notes = "停车场计费规则表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ChargeRules>> queryPageList(ChargeRules chargeRules,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Result<IPage<ChargeRules>> result = new Result<IPage<ChargeRules>>();
        QueryWrapper<ChargeRules> queryWrapper = QueryGenerator.initQueryWrapper(chargeRules, req.getParameterMap());
        Page<ChargeRules> page = new Page<ChargeRules>(pageNo, pageSize);
        IPage<ChargeRules> pageList = chargeRulesService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 获取指定区域，指定车辆类型的计费信息
     *
     * @param
     */
    @AutoLog(value = "停车场计费规则表-计费规则查询")
    @ApiOperation(value = "停车场计费规则表-计费规则查询", notes = "停车场计费规则表-计费规则查询")
    @PostMapping(value = "/getChargeRule")
    public Result<ChargeRules> getChargeRule(@RequestBody ChargeRules chargeRules) {
        Result<ChargeRules> result = new Result<>();
        LoginUser loginUser = LoginUserUtils.getLoginUser();
        LambdaQueryWrapper<ChargeRules> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(loginUser.getParkCode())) {
            queryWrapper.eq(ChargeRules::getParkCode, loginUser.getParkCode());
        } else {
            queryWrapper.eq(ChargeRules::getParkCode, chargeRules.getParkCode());
        }
        queryWrapper.eq(ChargeRules::getAreaId, chargeRules.getAreaId());
        queryWrapper.eq(ChargeRules::getCarTypeId, chargeRules.getCarTypeId());
        result.setResult(chargeRulesService.getOne(queryWrapper));
        return result;
    }

    /**
     * 添加
     *
     * @param chargeRules
     * @return
     */
    @AutoLog(value = "停车场计费规则表-添加")
    @ApiOperation(value = "停车场计费规则表-添加", notes = "停车场计费规则表-添加")
    @PostMapping(value = "/add")
    public Result<ChargeRules> add(@RequestBody ChargeRules chargeRules) {
        Result<ChargeRules> result = new Result<ChargeRules>();
        try {
            LoginUser loginUser = LoginUserUtils.getLoginUser();
            chargeRules.setId(SnowFlakeUtil.getId());
            chargeRules.setCreateUserId(loginUser.getId());
            chargeRules.setCreateUserName(loginUser.getUsername());
            chargeRules.setCreateTime(new Date());
            chargeRulesService.save(chargeRules);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param chargeRules
     * @return
     */
    @AutoLog(value = "停车场计费规则表-编辑")
    @ApiOperation(value = "停车场计费规则表-编辑", notes = "停车场计费规则表-编辑")
    @PutMapping(value = "/edit")
    public Result<ChargeRules> edit(@RequestBody ChargeRules chargeRules) {
        Result<ChargeRules> result = new Result<ChargeRules>();

        ChargeRules chargeRulesEntity = chargeRulesService.getById(chargeRules.getId());
        if (chargeRulesEntity == null) {
            result.error500("未找到对应实体");
        } else {
            LoginUser loginUser = LoginUserUtils.getLoginUser();
            chargeRules.setUpdateTime(new Date());
            chargeRules.setUpdateUserId(loginUser.getId());
            chargeRules.setUpdateUserName(loginUser.getUsername());
            boolean ok = chargeRulesService.updateById(chargeRules);

            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "停车场计费规则表-通过id删除")
    @ApiOperation(value = "停车场计费规则表-通过id删除", notes = "停车场计费规则表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            chargeRulesModuleService.removeByChargeRulesId(id);
            chargeRulesService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败,{}", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 计费测试接口
     *
     * @param areaId       区域id
     * @param carTypeId    车辆类型id
     * @param carEnterTime 入场时间
     * @param carOutTime   出场时间
     */
    @AutoLog(value = "停车场计费规则表-计费测试")
    @ApiOperation(value = "停车场计费规则表-计费测试", notes = "停车场计费规则表-计费测试")
    @GetMapping(value = "/testCharge")
    public Result<?> testCharge(String areaId, String carTypeId, String carEnterTime, String carOutTime) {
        try {
            Date carEnterTimeParam = DateUtils.stringToDate(carEnterTime, "yyyy-MM-dd HH:mm:ss");
            Date carOutTimeParam = DateUtils.stringToDate(carOutTime, "yyyy-MM-dd HH:mm:ss");
            ChargeRules chargeRules = chargeRulesService.getChargeRules(carTypeId,areaId);
            if(null == chargeRules)
            {
                throw new JddException(ResultCode.PARAMETER_ERROR,"未查询到计费规则: carTypeId:"+carTypeId);
            }
            List<ChargeRulesModule> chargeRulesModuleList = chargeRulesModuleService.getChargeRulesModule(chargeRules.getId());
            if(null == chargeRulesModuleList)
            {
                throw new JddException(ResultCode.PARAMETER_ERROR,"该计费规则设置错误: carTypeId:"+carTypeId);
            }
            Long totalFee =chargeFeeUtils.chargeEnterLogFee(carEnterTimeParam,carOutTimeParam,chargeRules);

            return Result.ok(totalFee);
        }catch (Exception e)
        {
            log.error("计费测试接口,错误信息：" + e);
            return Result.error("获取计费结果失败");
        }
    }

}
